import os
import pytest
from seleniumbase import BaseCase


class ImageTests(BaseCase):
    @pytest.mark.run(order=1)
    def test_pull_image_from_website(self):
        """ 从网站中提取图像并将其保存为 PNG 文件。"""
        self.open("https://xkcd.com/1117/")
        selector = "#comic"
        file_name = "comic.png"
        folder = "images_exported"
        self.save_element_as_image_file(selector, file_name, folder)
        self.assert_true(os.path.exists("%s/%s" % (folder, file_name)))
        print('\n"%s/%s" was saved!' % (folder, file_name))

    @pytest.mark.run(order=2)
    def test_add_text_overlay_to_image(self):
        """ 向图像添加文本。 """
        self.open("https://xkcd.com/1117/")
        selector = "#comic"
        file_name = "image_overlay.png"
        folder = "images_exported"
        overlay_text = 'This is an XKCD comic!\nTitle: "My Sky"'
        self.save_element_as_image_file(
            selector, file_name, folder, overlay_text
        )
        self.assert_true(os.path.exists("%s/%s" % (folder, file_name)))
        print('\n"%s/%s" was saved!' % (folder, file_name))

    @pytest.mark.run(order=3)
    def test_add_text_overlay_to_page_section(self):
        """ 将文本添加到页面的一部分(指定选择器即可)。 """
        self.open("https://xkcd.com/2200/")
        selector = "#middleContainer"
        file_name = "section_overlay.png"
        folder = "images_exported"
        overlay_text = (
            "Welcome to %s\n"
            "This is a comment added to the image.\n"
            "Unreachable states come from logic errors."
            % self.get_current_url()
        )
        self.save_element_as_image_file(
            selector, file_name, folder, overlay_text
        )
        self.assert_true(os.path.exists("%s/%s" % (folder, file_name)))
        print('\n"%s/%s" was saved!' % (folder, file_name))

    @pytest.mark.run(order=4)
    def test_add_text_overlay_to_full_page(self):
        """ 将文本添加到整个页面 """
        self.open("https://xkcd.com/1922/")
        self.remove_element("#bottom")
        selector = "body"
        file_name = "page_overlay.png"
        folder = "images_exported"
        overlay_text = "A text overlay on %s" % self.get_current_url()
        self.save_element_as_image_file(
            selector, file_name, folder, overlay_text
        )
        self.assert_true(os.path.exists("%s/%s" % (folder, file_name)))
        print('\n"%s/%s" was saved!' % (folder, file_name))
